from elasticsearch import Elasticsearch

def search_documents_generator(es_client,index_name, keyword, page_size=10):
    from_ = 0

    while True:
        query = {
            "query": {
                "match": {
                    "key": keyword
                }
            },
            "from": from_,
            "size": page_size
        }
        # 执行查询
        response = es_client.search(index=index_name, body=query)


        # 处理查询结果
        total_hits = response["hits"]["total"]["value"]  # 总命中数
        doc_hits = response["hits"]["hits"]  # 查询命中的文档列表

        if not doc_hits:
            break

        # 返回当前页的结果
        yield doc_hits, total_hits

        # 准备下一个请求：增加起始位置
        from_ += page_size

        # 如果我们已经达到总数，则停止迭代
        if from_ >= total_hits:
            break

# 使用示例
if __name__ == '__main__':
    # Elasticsearch服务地址
    ES_HOST = "http://localhost:9200" # 可以根据需要调整
    # 创建Elasticsearch客户端实例
    es_client = Elasticsearch(ES_HOST)
    # 索引名称
    INDEX_NAME = "component_library_module_search"          # 替换为你的索引名称
    # 要搜索的关键词
    KEYWORD = "张三"
    PAGE_SIZE = 2


    results_generator = search_documents_generator(es_client, INDEX_NAME, KEYWORD, PAGE_SIZE)

    for hits, total_hits in results_generator:
        print(f'Total hits: {total_hits}')
        for result in hits:
            print(result['_id'],result["_source"]["key"])
        
        # 可以在这里添加一个break来停止迭代，或者允许用户输入以决定是否继续获取下一页
        input("Press Enter to get the next page or Ctrl+C to stop...")

